import config from '@/config'
import {
	getToken,
	removeToken,
	setToken
} from '@/utils/auth'
import errorCode from '@/config/errorCode'
import {
	tansParams
} from '@/utils/common'
import toast from '@/plugins/toast.js'
import tab from '@/plugins/tab.js'

let timeout = 15000
const baseUrl = config.baseUrl
const request = config => {
	// 是否需要设置 token
	const isToken = (config.headers || {}).isToken === false
	config.header = config.header || {}
	if (getToken() && !isToken) {
		config.header['Authorization'] = 'Bearer ' + getToken()
	}
	// get请求映射params参数
	if (config.params) {
		let url = (config.baseUrl || config.url) + '?' + tansParams(config.params)
		url = url.slice(0, -1)
		if (config.baseUrl) {
			config.baseUrl = url
		} else {
			config.url = url
		}
	}
	return new Promise((resolve, reject) => {
		toast.loading('加载中', false)
		uni
			.request({
				method: config.method || 'get',
				timeout: config.timeout || timeout,
				url: config.baseUrl || baseUrl + config.url,
				data: config.data || {},
				header: config.header || 'application/json',
				dataType: 'json'
			})
			.then(response => {
				toast.closeLoading()
				let [error, res] = response
				if (error) {
					toast.msg('网络错误，请检查网络')
					reject('网络错误，请检查网络')
					return
				}
				const code = res.data.code || res.data.status || 200
				const msg = errorCode[code] || res.data.msg || errorCode['default']
				if (code === 401) {
					// 第一个接口返回401代表还存在token，后续接口不再提示
					if (getToken()) {
						removeToken()
					}
					toast.msg('登录状态已过期，请重新登录。', () => {
						tab.switchTab('/pages/mine/index')
					})
					return
				} else if (code === 500) {
					toast.msg(msg)
					reject(code)
				} else if (code !== 200) {
					toast.msg(msg)
					reject(code)
				}
				resolve(res.data)
			})
			.catch(error => {
				toast.closeLoading()
				let {
					message
				} = error
				if (message === 'Network Error') {
					message = '网络错误，请检查网络'
				} else if (message.includes('timeout')) {
					message = '网络请求超时'
				} else if (message.includes('Request failed with status code')) {
					message = '系统接口' + message.substr(message.length - 3) + '异常'
				}
				toast.msg(message)
				reject(error)
			})
	})
}

export default request